package com.example.project13;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;

public class GpsBindService extends Service {
    private static final String TAG = "GpsBindService";
    private static final int NOTIFICATION_ID = 1;
    private static final String CHANNEL_ID = "GpsServiceChannel";
    
    private GpsCallback gpsCallback;
    private FusedLocationProviderClient fusedLocationClient;
    private LocationCallback locationCallback;

    // GPS回调接口
    public interface GpsCallback {
        void onGpsUpdate(double latitude, double longitude);
    }

    // 自定义Binder类
    public class LocalBinder extends Binder {
        public GpsBindService getService() {
            return GpsBindService.this;
        }

        public void setGpsCallback(GpsCallback callback) {
            gpsCallback = callback;
        }
    }

    private final IBinder binder = new LocalBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "GpsBindService created");
        createNotificationChannel();
        startForeground(NOTIFICATION_ID, createNotification());
        initLocationManager();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "GPS Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }

    private Notification createNotification() {
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("GPS位置服务")
                .setContentText("正在获取位置信息...")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .build();
    }

    private void initLocationManager() {
        // 使用FusedLocationProviderClient（推荐方式）
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(@NonNull LocationResult locationResult) {
                Location location = locationResult.getLastLocation();
                if (location != null && gpsCallback != null) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    Log.d(TAG, "位置更新: 纬度=" + latitude + ", 经度=" + longitude);
                    gpsCallback.onGpsUpdate(latitude, longitude);
                    
                    // 更新通知
                    Notification notification = new NotificationCompat.Builder(GpsBindService.this, CHANNEL_ID)
                            .setContentTitle("GPS位置服务")
                            .setContentText(String.format("位置: 纬度 %.4f°, 经度 %.4f°", latitude, longitude))
                            .setSmallIcon(R.drawable.ic_launcher_foreground)
                            .build();
                    startForeground(NOTIFICATION_ID, notification);
                }
            }
        };

        // 创建位置请求
        LocationRequest locationRequest = LocationRequest.create()
                .setInterval(1000)
                .setFastestInterval(1000)
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        try {
            fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
        } catch (SecurityException e) {
            Log.e(TAG, "没有定位权限", e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "GpsBindService destroyed");
        if (fusedLocationClient != null && locationCallback != null) {
            fusedLocationClient.removeLocationUpdates(locationCallback);
        }
    }
}